﻿using Csb.SignalClient2.Model;
using Csb.SignalRClient2.Model;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csb.SignalClient2
{
    public partial class Form1 : Form
    {
        private HubConnection _hubConnection;
        public Form1(User user)
        {
            InitializeComponent();
        }

        private async void UpdateData_Click(object sender, EventArgs e)
        {
            //客户端调用服务器更新数据
            var user = new User() { UserName = this.username.Text.Trim(), UserPassord = this.password.Text.Trim() };
            //调用服务端，ChatHub类中的方法UpdateMessage，接收客户端发送的更新数据
            await _hubConnection.InvokeAsync("UpdateMessage", new MsgInfo { user = JsonConvert.SerializeObject(user), message = "更新成功" });

            this.Invoke(new Action(() =>
            {
                this.richTextBox1.AppendText($"{JsonConvert.SerializeObject(user)}\r\n");
            }));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {

                _hubConnection = new HubConnectionBuilder()
               .WithUrl("http://localhost:8081/signalchat") //指定服务器的hub端点地址
               .WithAutomaticReconnect() //支持重连，可自定义配置
               .Build();

                // 订阅服务器端发送的消息，绑定客户端方法，指定名字，不然服务器不知道调用谁
                _hubConnection.On<MsgInfo>("ShowMsg", (msg) =>
                {
                    //// 处理接收到的消息
                    // 确保在 UI 线程中更新 TextBox
                    this.Invoke(new Action(() =>
                    {
                        this.receiveMsg.AppendText($"{msg.user}: {msg.message}\r\n");
                    }));

                });

                //在线人列表
                _hubConnection.On<User[]>("UpdateUserList", (users) =>
                {
                    //this.userList.Invoke((MethodInvoker)delegate
                    //{
                    //    this.userList.Items.Clear();
                    //    this.userList.Items.AddRange(users);
                    //});
                });

                //在线人数
                _hubConnection.On<int>("UpdateOnlineCount", (count) =>
                {
                    this.userOnline.Invoke((MethodInvoker)delegate
                    {
                        userOnline.Text = $"{count}";
                    });
                });


                // 启动连接
                _hubConnection.StartAsync().ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        MessageBox.Show($"Error connecting to SignalR Hub: {task.Exception?.InnerExceptions[0]}");
                    }
                    else
                    {
                        //MessageBox.Show("Connected to SignalR Hub");
                    }
                });

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private async void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_hubConnection != null)
            {
                await _hubConnection.StopAsync();
                Application.Exit();
            }

        }
    }
}
